#!/bin/bash

# standard paths
PATH="${PATH}:/usr/bin:/bin"
MULTIPATH="/sbin/multipath"

# print usage help
usagehelp(){
cat << EOF
Usage: lld-blockdev [OPTION]... 
Lists available block devices in JSON format.
Intended for Zabbix LLD (Low Level Discovery)

Mandatory arguments to long options are mandatory for short options too.
  -s, --sds                  list storage devices (eg. sda)
  -x, --xvds                 list virtual devices (eg. xvda)
  -d, --dms                  list mapped devices (eg. dm-5)
  -m, --mdraid               list mdraid devices (eg. md3)
  --skip-mpath               skip devices used by multipath
  -h, --help                 display this help and exit

EOF
exit 1
}

# set defaults
DISK_IN_MPATH=1

# read the options
ARGS=$( getopt -o sxdmh --long sds,xvds,dms,mdraid,help,skip-mpath -n 'lld-blockdevices' -- "$@" );
eval set -- "$ARGS"

# extract options and their arguments into variables.
while true ; do
    case "$1" in
        -s|--sds)    sds=`find /dev -maxdepth 1 -type b -iname sd*  | awk '{print $NF}' | sed 's/[0-9]//g' | sort | uniq`; shift ;;
        -x|--xvds)   xvs=`find /dev -maxdepth 1 -type b -iname xvd* | awk '{print $NF}' | sed 's/[0-9]//g' | sort | uniq`; shift ;;
        -d|--dms)    dms=`find /dev -maxdepth 1 -type b -iname dm-* | awk '{print $NF}' | sort | uniq`; shift ;;
        -m|--mdraid) mds=`find /dev -maxdepth 1 -type b -iname md*  | awk '{print $NF}' | sort | uniq`; shift ;;
        --skip-mpath) SKIP_MPATH="true"; shift ;;
        --) shift ; break ;;
        *) usagehelp ; exit 1 ;;
    esac
done

echo "{"
echo "\"data\":["

for blockdev in $sds $xvs $mds $dms; do
    if [ ! -z $LAST_DEV ]; then
        [ "xx$SKIP_MPATH" == "xxtrue" -a -x $MULTIPATH ] && sudo $MULTIPATH -ll 2>/dev/null | grep -q "${LAST_DEV:5} "
        DISK_IN_MPATH=$?
        [ $DISK_IN_MPATH -ne 0 ] && echo "    {\"{#BLOCKDEVNAME}\":\"$LAST_DEV\",\"{#BLOCKDEVNAMESHORT}\":\"${LAST_DEV:5}\"},"
    fi
    LAST_DEV=$blockdev
done
[ "xx$blockdev" != "xx" ] && echo "    {\"{#BLOCKDEVNAME}\":\"$blockdev\",\"{#BLOCKDEVNAMESHORT}\":\"${blockdev:5}\"}"

echo "]"
echo "}"

exit 0
